import { get } from "../../utils/request";

Page({
  data: {
    tabs: ["vue", "css", "html", "js", "react", "typescript", "node"],
    currentIndex: -1,
    interviews: [],
    swiperHeight: 150, //定义最外层的轮播图的高度
    audioManager: null, //后台音频播放管理器的实例
    playingInterviewId: "", //当前正在播放器的面试的ID
  },
  onLoad() {
    this.changeCurrentIndex(0);
    this.initAudioManager();
  },
  initAudioManager() {
    const audioManager = wx.getBackgroundAudioManager();
    this.setData({ audioManager });
    //监听音频管理 器的暂停事件，当点击暂停的时候把playingInterviewId设置为空串
    audioManager.onPause(() => {
      this.setData({ playingInterviewId: "" });
    });
  },
  // 切换播放状态
  togglePlay(event) {
    console.log(event.currentTarget.dataset);
    const { _id, title, url } = event.currentTarget.dataset.interview;
    if (!url) {
      return wx.showToast({
        title: `音频文件不存在`,
      });
    }
    const { audioManager, playingInterviewId } = this.data;
    if (playingInterviewId === _id) {
      audioManager.pause(); //暂停播放
      this.setData({ playingInterviewId: "" });
    } else {
      audioManager.title = title; //设置标题
      audioManager.src = url; //设置播放的音频地址，一旦赋值则自动播放
      this.setData({ playingInterviewId: _id }); //设置当前正在播放的音频ID
    }
  },
  changeCurrentIndex(currentIndex) {
    this.setData(
      {
        currentIndex,
      },
      () => {
        //更新后的回调
        this.getInterviews();
      }
    );
  },
  async getInterviews() {
    //获取当前的选中的面试题分类
    let type = this.data.tabs[this.data.currentIndex];
    //调用接口获取此分类下面的面试题
    let { interview: interviews } = await get("/interview", {
      data: { type },
    });
    this.setData({ interviews }, () => {
      //获取内容的高度，再通过内容的高度设置窗口swiper的高度
      const query = wx.createSelectorQuery();
      query
        .select(`.swiper-item-${this.data.currentIndex}`) //指定一个选择器
        .boundingClientRect() //获取宽高和位置 信息
        .exec((rect) => {
          //执行查询 ，因为执行是异步的，所以需要通过回调函数获取结果
          const height = rect[0].height;
          this.setData({
            swiperHeight: height,
          });
        });
    });
  },
  tabChange(event) {
    //获点击事件对象上上的当前的事件源，对应的数据集中上的索引
    this.changeCurrentIndex(event.currentTarget.dataset["index"]);
  },
  swiperChanged(event) {
    this.changeCurrentIndex(event.detail.current);
  },
  onHide() {
    this.stopAudio();
  },
  onUnload() {
    this.stopAudio();
  },
  stopAudio() {
    this.data.audioManager.stop();
  },
});
